<template>
	<view class="storecart skinStyle1">
		<view class="com-top" v-if="cartList.length>0">
			<view class="left-text">购物车共<text class="red">{{cartList.length}}</text>种商品</view>
			<view @click="editCart">
				<i class="line"></i>
				<text class="cart-text">{{delBtnFlag?'完成':'编辑'}}</text>
			</view>
		</view>
		<template v-if="cartList.length>0">
			<scroll-view scroll-y="true" class="storecart-con" :scroll-into-view="'item'+curId"
				:scroll-with-animation="true" :enable-back-to-top="true">
				<view class="tui-cart-cell" v-for="(item, index) in cartList" :key="index" :id="'item'+item.id">
					<tui-swipe-action :actions="actions" @click="handlerButton" :params="item" class="swipe-action">
						<template v-slot:content>
							<view class="tui-goods-item-wrap">
								<checkbox-group @change="selectSingle(item)" class="tui-checkbox">
									<checkbox :value="item.id" :checked="item.checked" color="#fff" />
								</checkbox-group>
								<view class="tui-goods-item">
									<view class="tui-goods-img">
										<image v-if="item.imgList&&item.imgList.length>0"
											:src="imgSrc + item.imgList[0].imgReuri" />
									</view>
									<view class="tui-goods-info">
										<view class="tui-goods-title">{{ item.goodsName }} {{item.goodsMatcode}}</view>
										<view class="tui-goods-sub">产品码：
											<text
												v-if="item.uniqueCodeList&&item.uniqueCodeList.length==1">{{item.uniqueCodeList[0].goodsCode}}</text>
											<text class="code-text"
												v-if="item.uniqueCodeList&&item.uniqueCodeList.length>1"
												@tap="viewCodesModal($event,index,item.uniqueCodeList)">{{item.uniqueCodeList[0].goodsCode}}<text
													class="icon-sj red iconfont iconxiasanjiaoxing"></text></text>
										</view>
										<!-- <view class="tui-goods-sub">状态：{{ item.isShelf==1?'上架':'下架' }}</view> -->
										<view class="tui-goods-sub">状态：待支付</view>
										<view class="tui-price-box">
											<view class="tui-goods-price">￥{{ item.goodsPrice}}</view>
											<view class="tui-goods-num">x{{ item.buyNum}}</view>
										</view>
									</view>
								</view>
							</view>
						</template>
					</tui-swipe-action>
				</view>

			</scroll-view>
		</template>
		<view class="tui-tabbar">
			<checkbox-group @tap="selectAll" class="check-group" v-if="cartList.length>0">
				<label class="tui-checkbox">
					<checkbox value="all" :checked="allChecked" color="#fff"></checkbox>
				</label>
			</checkbox-group>
			<view class="tui-tabbar-left">
				<view class="tabbar-customer">顾客:{{memberCode}}</view>
				<view class="tui-total-price">合计:<text>￥{{ totalPrice }}</text></view>
			</view>
			<view class="storecart-btn">
				<tui-button width="190rpx" height="80rpx" :size="30" type="yellow" shape="circle" @tap="scanShow">
					{{cartList.length>0?'继续购买':'扫一扫'}}
				</tui-button>
				<tui-button v-if="delBtnFlag" width="190rpx" height="80rpx" :size="30" type="black" shape="circle"
					@tap="deleteClick" :disabled="cartList.length===0||!totalPrice" :plain="true">删除</tui-button>
				<tui-button v-else width="190rpx" height="80rpx" :size="30" type="danger" shape="circle" @tap="btnPay"
					:disabled="cartList.length===0||!totalPrice">结算</tui-button>
			</view>
		</view>

		<!-- 商品唯一码列表 -->
		<view class="code-mask" v-if="codeFlag" @tap="hideCodesModal"></view>
		<view class="code-list" :style="{top:codeModalTop,bottom:codeModalBottom}" v-if="codeFlag">
			<!-- <view class="code-close iconfont iconguanbi3"></view> -->
			<view class="code-list-title">
				<view class="code">产品码</view>
				<view class="status">状态</view>
			</view>
			<view class="code-list-con">
				<view class="code-list-item" v-for="item in codeList">
					<view class="code">{{item.goodsCode}}</view>
					<view class="status">待支付</view>
				</view>
			</view>
		</view>
		<!-- 扫码功能 -->
		<!-- 兼容微信小程序 -->
		<!-- #ifdef MP-WEIXIN -->
		<view class="scan-wrap" v-if="scanFlag">
			<camera-scan :scanTip="scanTip" @close="closeScan" @scanCode="scanCode"></camera-scan>
		</view>
		<!-- #endif -->

		<mix-empty v-if="cartList.length===0" :type="'default'" :backgroundColor="'#fff'"></mix-empty>
		<loading></loading>
		<tui-modal></tui-modal>
	</view>
</template>
<script>
	import mixEmpty from '@/components/mix-empty/mix-empty.vue'
	import tuiSwipeAction from '@/components/swipe-action/swipe-action';
	import tuiButton from '@/components/button/button';
	// #ifdef MP-WEIXIN
	import cameraScan from "@/packageC/components/camera/camera.vue"
	// #endif
	export default {
		components: {
			mixEmpty,
			tuiSwipeAction,
			tuiButton,
		
			// #ifdef MP-WEIXIN
			cameraScan,
			// #endif
		},
		data() {
			return {
				cartList: [],
				imgSrc: this.$store.state.imgUrl,
				totalPrice: 0,
				scanFlag: false,
				scanTip: '请扫描商品二维码',
				allChecked: true,
				actions: [{
					name: '删除',
					color: '#fff',
					fontsize: 30, //单位rpx
					width: 70, //单位px
					background: '#EA655E'
				}],
				goodsUniqueCode: '',
				customerUserId: '',
				scanFlag: false,
				codeFlag: false, //显示产品码
				codeList: [], //当前产品码列表
				isLoading: false,
				curId: '', //当前滚动id
				staffId: '',
				staffName: '',
				jxsId: '',
				jxsName: '',
				customerUserId: '',
				userName: '',
				
				delBtnFlag: false,
				infoFlag: false, //判断人员信息是否存在
				memberCode: uni.getStorageSync('memberCode'),
				codeModalTop: '0rpx',
				codeModalBottom: '0rpx',
				windowHeight: 0,
				backFlag: true, //监听头部返回
				
				orgLv:'',
			};
		},
		onLoad(options) {
			if(uni.getStorageSync('storeOrgLv')){
				this.orgLv=uni.getStorageSync('storeOrgLv')
			}else{
				this.orgLv=uni.getStorageSync('orgLv')
			}
			let that = this;
			// #ifdef H5
			this.$wechat.noShare();
			// #endif

			this.goodsUniqueCode = options.goodsUniqueCode;
			this.customerUserId = options.customerUserId;
			
			this.getStoreCart();
			// 监听页面刷新
			this.$eventHub.$off('storeCartRefresh');
			this.$eventHub.$on('storeCartRefresh', () => {
				that.deleteClick()
			});
			//获取屏幕高度
			uni.getSystemInfo({
				success: function(res) {
					that.windowHeight = res.windowHeight;
				}
			})
			
		},
		onShow() {
			// #ifdef APP-PLUS
			this.$eventHub.$off('appScanCode');
			this.$eventHub.$on('appScanCode',(codeRes) => {
				this.scanCode(codeRes)
			});
			// #endif
		},
		methods: {
			scanShow() {
				// #ifdef MP-WEIXIN
				this.scanFlag = true;
				// #endif
				
				// #ifdef APP-PLUS
				uni.navigateTo({
					url:'/packageC/pages/scan/scan'
				})
				// #endif
				
				// #ifdef H5
				this.$wechat.scanQRCode((str) => {
					//str为扫码结果
					this.scanCode(str)
				});
				// #endif
			},
			closeScan() {
				this.scanFlag = false;
			},
			getStoreCart() {
				let params = {
					goodsUniqueCode: this.goodsUniqueCode,
					customerUserId: this.customerUserId,
					orgLv:this.orgLv,
					loginId:uni.getStorageSync('agencyId'),
					loginName:uni.getStorageSync('storeOrgName'),
				}
				this.$http.storeCart(params).then((res) => {
					if (res.status === 0) {
						this.cartList = res.data.records;
						this.staffId = res.data.staffId
						this.staffName = res.data.staffName
						this.jxsId = res.data.jxsId
						this.jxsName = res.data.jxsName
						this.customerUserId = res.data.customerUserId
						if(res.data.userName){
							this.userName = res.data.userName
						}else{
							this.userName = res.data.nickName
						}
						
						this.infoFlag = true;
						this.cartList[0].checked = true
						this.getTotalPrice()
					}
				})
			},
			handlerButton(e) { //删除
				this.cartList.splice(e.index, 1)
				this.getTotalPrice()
			},
			deleteClick() {
				let cartListNew = [];
				//删除那些选择的
				this.cartList.forEach((item, index) => {
					if (!item.checked) {
						cartListNew.push(item);
					}
				});
				this.cartList = cartListNew;
				this.totalPrice = 0;
			},
			scanCode(codeRes) {
				let that = this;
				if (codeRes.indexOf("=") > -1) {
					let goodsUniqueCode = codeRes.split("=")[1]; //商品唯一码
					let goodsCode=goodsUniqueCode.slice(0,16)
			
					if (goodsUniqueCode.length !== 29) {
						that.scanTip = '请扫描正确的商品二维码';
						uni.showToast({
							icon: 'none',
							title: '请扫描正确的商品二维码',
							duration: 1000,
						})
						// #ifdef H5
						setTimeout(() => {
							that.$wechat.scanQRCode((str) => {
							that.scanCode(str)
							});
						}, 1000);
						// #endif
						return;
					}

					if (that.cartList.length > 0) {
						for (let i = 0; i < that.cartList.length; i++) {
							for (let j = 0; j < that.cartList[i].uniqueCodeList.length; j++) {
								if (that.cartList[i].uniqueCodeList[j].goodsCode == goodsCode) {
									uni.showToast({
										icon: 'none',
										title: '该商品已扫描过，请扫描其他商品',
										duration: 1000,
									})
									// #ifdef H5
									setTimeout(() => {
										that.$wechat.scanQRCode((str) => {
										that.scanCode(str)
										});
									}, 1000);
									// #endif
									return;
								}
							}
						}
					}

					let params = {
						goodsUniqueCode: goodsUniqueCode,
						customerUserId: that.customerUserId,
						orgLv:this.orgLv,
						loginId:uni.getStorageSync('agencyId'),
						loginName:uni.getStorageSync('storeOrgName'),
					}
					that.$http.storeCart(params).then((res) => {
						if (res.status === 0) {
							this.scanFlag = false;
							// #ifdef APP-PLUS
							this.$eventHub.$emit('appScanClose');
							// #endif
							if (!this.infoFlag) {
								this.staffId = res.data.staffId
								this.staffName = res.data.staffName
								this.jxsId = res.data.jxsId
								this.jxsName = res.data.jxsName
								this.customerUserId = res.data.customerUserId
								this.userName = res.data.userName
								this.infoFlag = true;
							}
							let flag = false; //所扫商品是否在购物车已经存在
							let curGoods = res.data.records[0];
							curGoods.checked = false;
							if (that.cartList.length > 0) {
								for (let i = 0; i < that.cartList.length; i++) {
									if ((that.cartList[i].id === curGoods.id) && (that.cartList[i].goodsMatcode ===
											curGoods.goodsMatcode)) {
										that.cartList[i].uniqueCodeList.push(curGoods.uniqueCodeList[0]);
										that.cartList[i].buyNum += 1;
										flag = true;
										break;
									}
								}
							}
							if (!flag) { //不存在
								that.cartList.push(curGoods);
							}
							uni.showToast({
								title: '商品扫描码成功',
								duration: 1000,
							})

							this.curId = curGoods.id;
							this.cartList.map(item => {
								item.checked = true
							})
							this.allChecked = true
							this.getTotalPrice()
						} else {
							this.scanFlag = false;
							// #ifdef APP-PLUS
							this.$eventHub.$emit('appScanClose');				
							// #endif
						}
					}).catch(()=>{
						this.scanFlag = false;
						// #ifdef APP-PLUS
						this.$eventHub.$emit('appScanClose');				
						// #endif
					})
				}else{
					that.scanTip = '请扫描正确的商品二维码';
					uni.showToast({
						icon: 'none',
						title: '请扫描正确的商品二维码',
						duration: 1000,
					})
					
					// #ifdef H5
					setTimeout(() => {
						that.$wechat.scanQRCode((str) => {
						that.scanCode(str)
						});
					}, 1000);
					// #endif
				}
			},
			editCart() {
				this.delBtnFlag = !this.delBtnFlag;
			},

			viewCodesModal(e, index, list) {
				console.log(e.target.y);
				console.log(this.windowHeight)
				if (this.windowHeight > (e.target.y + 300)) {
					this.codeModalTop = e.target.y + 20 + 'px'
					this.codeModalBottom = 'auto';

				} else {
					this.codeModalTop = 'auto';
					this.codeModalBottom = this.windowHeight - (e.target.y - 20) + 'px';
				}

				this.codeFlag = true
				this.codeList = list;
			},
			hideCodesModal() {
				this.codeFlag = false
			},
			// 结算
			btnPay() {
				let selectedList = [];
				this.cartList.forEach(item => {
					if (item.checked) {
						selectedList.push(item)
					}
				})
				let params = {
					staffId: this.staffId,
					staffName: this.staffName,
					jxsId: this.jxsId,
					jxsName: this.jxsName,
					customerUserId: this.customerUserId,
					userName: this.userName,
					goodsList: selectedList,
					orgLv:this.orgLv,
					loginId:uni.getStorageSync('agencyId'),
					loginName:uni.getStorageSync('storeOrgName'),
				}

				this.$http.storeCartSettlement(params).then((res) => {
					if (res.status == 0) {
						let orderId = res.data.id;
						let version = res.data.version;
						console.log(this.version)
						this.backFlag = false;
						uni.navigateTo({
							url: `/packageC/pages/storeCart/cartSettlement?orderId=${orderId}&version=${version}`
						});
						
					}
				})
			},
			getTotalPrice() {
				this.totalPrice = 0;
				this.cartList.forEach((item, index) => {
					if (item.checked) {
						this.totalPrice += item.goodsPrice * item.buyNum;
					}
				});
			},
			// 单个商品的选择
			selectSingle(item) {
				item.checked = !item.checked
				if (!item.checked) {
					this.allChecked = false
				} else {
					// 判断每一个商品是否是被选择的状态
					const cartList = this.cartList.every(item => {
						return item.checked === true
					})
					if (cartList) {
						this.allChecked = true
					} else {
						this.allChecked = false
					}
				}
				this.getTotalPrice()
			},
			//全选、全不选
			selectAll() {
				this.allChecked = !this.allChecked
				if (this.allChecked) {
					this.cartList.map(item => {
						item.checked = true
					})
				} else {
					this.cartList.map(item => {
						item.checked = false
					})
				}
				this.getTotalPrice()
			},
		},
		
	};
</script>

<style lang="scss">
	@import "@/packageC/static/style/common.scss";

	.storecart {
		width: 100%;
		height: 100vh;
		position: relative;
		padding-bottom: calc(constant(safe-area-inset-bottom) + 136rpx);
		padding-bottom: calc(env(safe-area-inset-bottom) + 136rpx);
		overflow-y: auto;
		padding-top: 76rpx;

		.storecart-con {
			height: calc(100vh - 200rpx);
			overflow-y: auto;
		}

		.tui-cart-cell {
			width: 100%;

			background: #ffffff;
			overflow: hidden;
			margin-top: 16rpx;

			.tui-goods-item-wrap {
				width: 100%;
				padding: 30rpx;
				display: flex;

				.tui-checkbox {
					width: 55rpx;
					display: flex;
					align-items: center;
					float: left;
					margin-right: 10rpx;
				}
			}
		}

		.tui-tabbar {
			width: 100%;
			padding: 24rpx 30rpx 30rpx;
			display: flex;

			align-items: center;
			padding-bottom: calc(constant(safe-area-inset-bottom) + 30rpx);
			padding-bottom: calc(env(safe-area-inset-bottom) + 30rpx);

			.tui-checkbox {
				width: 60rpx;
				margin-right: 10rpx;
			}

			.tui-tabbar-left {
				flex: 1;

				.tabbar-customer {}

				.tui-total-price {
					margin-top: 6rpx;
					color: $red;
					font-size: 32rpx;
				}

			}

			.storecart-btn {
				width: 396rpx;
				display: flex;
				justify-content: space-between;
			}
		}


	}

	/deep/ .uni-scroll-view::-webkit-scrollbar {
		/* 隐藏滚动条，但依旧具备可以滚动的功能 */
		display: none;
	}
</style>
